var FormRow = EventDispatcher.extend({

    VALIDATION_MESSAGES: {
        required: "Заполните поле.",
        number:   "Введите число.",
        min: "Введите неотрицательное число"
    },

    _form: null,
    _validationRules: null,
    _ajaxHandlerUrl: null,
    _inputFields: null,

    constructor: function(object, validationRules)
    {
        this._form = $(object);
        this._validationRules = validationRules;
        this._ajaxHandlerUrl = this._form.attr('action');
        this._inputFields = this._form.find('input[type="text"],input[type="hidden"],select');
        this._form.validate(this._prepareValidatorSettings());
        this._form.find('input[type="file"]').bind('change', handler(this, '_onFileInputChange'));
    },

    _getFormSubmitParams: function()
    {
        var thisPtr = this;
        var formSubmitParams = {};
        this._inputFields.each(function() {
            var curEl = $(this);
            formSubmitParams[curEl.attr('name')] = curEl.val();
        });
        return formSubmitParams;
    },

    _onSubmit: function()
    {
        var submitParams = this._getFormSubmitParams();
        $.ajax({
            type: 'post',
            url: this._ajaxHandlerUrl,
            data: submitParams,
            dataType: 'json',
            success: handler(this, '_onAjaxSuccess')
        });
        return false;
    },

    _onAjaxSuccess: function(response)
    {
        this.dispatchEvent(FormRow.AJAX_SUCCESS_EVENT, response);
    },

    _prepareValidatorSettings: function()
    {
        return {
            onfocusout: false,
            focusInvalid: false,
            focusCleanup: true,
            onkeyup: false,
            submitHandler: handler( this, '_onSubmit' ),

            rules: this._validationRules.getRules(),
            messages: this._validationRules.getMessages()
        };
    },

    _onFileInputChange: function(evt)
    {
        var targetId = $(evt.target).attr('id');
        $.ajaxFileUpload({
            url: '/file_upload_handler.php',
            secureuri:false,
            fileElementId: targetId,
            dataType: 'json',
            success: handler(this, "_onFileUploadSuccess"),
            error: handler(this, "_onFileUploadError")
        });
    },

    _onFileUploadSuccess: function (data, status)
    {
        if (typeof(data.error) != 'undefined')
        {
            if (data.error != '')
            {
                alert(data.error);
            }
            else
            {
                this._form.find('input[name="photo_link"]').val(data.photo_link);
            }
        }
    },

    _onFileUploadError: function (data, status, e)
    {
        alert(e);
    }

}, {
    AJAX_SUCCESS_EVENT: 'ajaxSuccess'
});